package ru.pb.game.network.engine.auth;

import org.apache.log4j.Logger;

import ru.pb.game.network.clients.AuthServerClient;
import ru.pb.game.network.engine.auth.packets.AuthServerToGameServerPacket;
import ru.pb.game.network.engine.auth.packets.receivable.AUTH_RESPONSE;
import ru.pb.game.network.engine.auth.packets.receivable.LOGIN_SERVER_FAIL;
import ru.pb.global.network.engine.buffer.NioBuffer;
import ru.pb.global.network.engine.core.emuns.ConnectionState;
import ru.pb.global.network.engine.core.interfaces.IPacketHandler;
import ru.pb.global.network.utils.NetworkUtil;

/**
 * Слушает пакеты от АУТХ Сервера.
 * 
 * @author Felixx
 */
public class AuthServerPacketListenerHandler implements IPacketHandler<AuthServerClient>
{
	private static final Logger _log = Logger.getLogger(AuthServerPacketListenerHandler.class);
	private boolean _aviableConnections = true;

	@Override
	public AuthServerToGameServerPacket handle(NioBuffer buf, AuthServerClient client)
	{
		boolean SHOW_ALL_PACKET = false;
		if(SHOW_ALL_PACKET)
		{
			NioBuffer temp = buf;
			int allSize = temp.limit();
			int position = temp.position();
			int opcode = temp.getUnsignedShort();
			_log.info("Packet id: " + opcode + "; size: " + allSize + "; pos:" + position);
		}

		ConnectionState state = client.getState();
		int opcode = buf.getUnsignedShort();
		// _log.info("Packet id: " + opcode + "; size: " + buf.limit() + "; pos:" + buf.position());
		AuthServerToGameServerPacket packet = null;

		if(_aviableConnections)
		{
			switch(state)
			{
				case CONNECTED:
				{
					switch(opcode)
					{
						case 0x00:
						{
							break;
						}
						case 0x01:
						{
							packet = new LOGIN_SERVER_FAIL();
							break;
						}
						case 0x02:
						{
							packet = new AUTH_RESPONSE();
							break;
						}
						default:
						{
							debugOpcode(opcode, state, client, buf);
							break;
						}
					}
					break;
				}
			}
			return packet;
		}
		return null;
	}

	private void debugOpcode(int opcode, ConnectionState state, AuthServerClient client, NioBuffer buf)
	{
		_log.info("Unknown Opcode: " + opcode + " for state: " + state.name() + " from IP: " + client.getIPString());
		_log.info(NetworkUtil.printData(buf));
	}
}